import React, { useState } from "react";
import { LoginApi, RegisterApi } from "@/api/index";
import logo from "@/assets/images/logo.png";
import "./index.less";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { Dispatch } from "redux";
import { useToast } from "@/util/toast";

export default function Login() {
  const [isLoginPage, setIsLoginPage] = useState(true);
  const [username, setUserName] = useState("18819291270");
  const [password, setPassword] = useState("wolfcode123");
  // const dispatch = useDispatch<Dispatch<IToastAction>>();
  const toast = useToast();
  const navigate = useNavigate();
  const login = () => {
    LoginApi({
      username,
      password,
    }).then((res) => {
      // console.log(res.data);
      if (res.errCode === 0) {
        // console.log(res);
        localStorage.setItem("token", res.data);
        // dispatch({
        //   type: "Toast_Show",
        //   payload: {
        //     type: "success",
        //     message: "登录成功",
        //   },
        // });
        toast("success", "登录成功");
        navigate("/home");
        // HomePageApi();
      }
    });
  };
  const register = () => {
    RegisterApi({
      phone: username,
      password,
    }).then((res) => {
      console.log(res);
      if (res.errCode === 0) {
        // alert("注册成功");
        toast("success", "注册成功");
        setIsLoginPage(true);
      }
    });
  };
  const btnClick = () => {
    isLoginPage ? login() : register();
  };
  return (
    <div className="login">
      <img src={logo} alt="" />
      <section className="form">
        <TextField
          value={username}
          onChange={(e) => setUserName(e.target.value)}
          variant="outlined"
          placeholder="请输入用户名"
        />
        <TextField
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          variant="outlined"
          placeholder="请输入密码"
        />
        <Button variant="contained" onClick={btnClick}>
          {isLoginPage ? "登录" : "注册"}
        </Button>
      </section>
      <div className="exchange">
        <span className="exchange" onClick={() => setIsLoginPage(!isLoginPage)}>
          去{isLoginPage ? "注册" : "登录"}
        </span>
      </div>
    </div>
  );
}
